package com.rc.saas.tenant.controller.msg;

import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.config.TransactionAdviceConfig;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.msg.TenantReceive;
import com.rc.saas.tenant.model.msg.TenantReceiveExample;
import com.rc.saas.tenant.model.msg.TenantUserReceive;
import com.rc.saas.tenant.model.msg.TenantUserReceiveExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.msg.TenantReceiveSearch;
import com.rc.saas.tenant.service.msg.TenantReceiveService;
import com.rc.saas.tenant.service.msg.TenantUserReceiveService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/tenantReceive")
public class TenantReceiveController {
    private static Logger logger = LogManager.getLogger(TenantReceiveController.class);

    @Autowired
    private TenantReceiveService tenantReceiveService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private TenantUserReceiveService tenantUserReceiveService;

    /**
     * 跳转运营商接收平台通知页面
     * @return
     */
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String tenantReceivePage(){
        return "/templates/msg/tenantReceive";
    }

    /**
     * 返回运营商接收平台通知列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageTenantReceive", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo pageTenantNotice(TenantReceiveSearch search) {
        TenantUser user=ShiroUtils.getSessionUser();
        search.setUserId(user.getTenantUserId());
        PageInfo<TenantReceive> pageInfo = tenantReceiveService.pageTenantNotice(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转消息通知详情页面
     *
     * @return
     */
    @RequestMapping(value = "/detailTenantReceive/{receiveId}", method = RequestMethod.GET)
    public String detailPile(@PathVariable("receiveId") Long receiveId, Model model) {
        TenantReceive tenantReceive=tenantReceiveService.selectByPrimaryKey(receiveId);
        TenantUser tenantUser= ShiroUtils.getSessionUser();
        TenantUserReceiveExample tenantUserReceiveExample=new TenantUserReceiveExample();
        tenantUserReceiveExample.createCriteria().andTenantUserIdEqualTo(tenantUser.getTenantUserId()).andReceiveIdEqualTo(receiveId);
        TenantUserReceive tenantUserReceive=tenantUserReceiveService.selectByExample(tenantUserReceiveExample).get(0);
        //修改消息为已读状态
        tenantReceive.setStatus("1");
        tenantReceiveService.updateByPrimaryKeySelective(tenantReceive);
        tenantUserReceive.setStatus("1");
        tenantUserReceiveService.updateByPrimaryKeySelective(tenantUserReceive);
        model.addAttribute("tenantReceive", tenantReceive);
        return "/templates/msg/detailTenantReceive";
    }

    /**
     * 下载通知文件
     *
     * @return
     */
    @RequestMapping(value = "/tenantReceiveDownLoad", method = RequestMethod.GET)
    @ResponseBody
    public TResponse AcctContractDownload(String file, String fileName, HttpServletResponse response) {
        try {

            String fileNameEndName = file.substring(file.length() - 4, file.length());
            String imgPath = upYunConfig.getDownloadRoot() + file;
            URL url = new URL(imgPath);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            OutputStream fileOutputStream = response.getOutputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");

            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8") + fileNameEndName);
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            // response.setHeader("Content-disposition", "attachment; filename=" + (imgPath.substring(imgPath.lastIndexOf("/") + 1, imgPath.length())));

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("下载平台端通知失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 返回运营商用户未读消息数
     * @return
     */
    @RequestMapping(value = "/tenantReceiveIsRead",method = RequestMethod.GET)
    @ResponseBody
    public TResponse tenantReceiveIsRead(){
        TenantUser tenantUser= ShiroUtils.getSessionUser();
        TenantUserReceiveExample example=new TenantUserReceiveExample();
        example.createCriteria().andTenantUserIdEqualTo(tenantUser.getTenantUserId()).andStatusEqualTo("0");
        long count=tenantUserReceiveService.countByExample(example);
        return TResponse.SUCCESS_DATA(count);
    }


}
